/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.BussinessLog;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.Const;
import cn.emove.core.common.constant.dictmap.UserDict;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.shiro.ShiroKit;
import cn.emove.core.shiro.ShiroUser;
import cn.emove.core.util.BPMInterfaceUtil;
import cn.emove.core.util.HttpUtil;
import cn.emove.modular.system.entity.MeterReading;
import cn.emove.modular.system.model.MeterDto;
import cn.emove.modular.system.model.OrderDto;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.MeterReadingService;
import cn.emove.modular.system.service.MeterService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.MeterReadingWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/meterReadingHandle")
public class MeterReadingHandleController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(MeterReadingHandleController.class);


    private static String PREFIX = "/modular/system/meter/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private MeterReadingService meterReadingService;

    @Autowired
    private MeterService meterService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;


    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "meterReadingHandle.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String meterNo,
                       @RequestParam(required = false) String shopName,
                       @RequestParam(required = false) String shopAdr,
                       @RequestParam(required = false) String monthTime,
                       @RequestParam(required = false) String auditStatus,
                       @RequestParam(required = false) String meterType,
                       @RequestParam(required = false) String meterModel) {

        //拼接查询条件
        if (ToolUtil.isNotEmpty(monthTime)) {
            monthTime = monthTime.replace("-","");

        }
        String selectFlag = "2";
        Page<Map<String, Object>> meterReadings = meterReadingService.selectMeterReadings(null, meterNo,shopName, shopAdr, monthTime,auditStatus,meterType,selectFlag, meterModel);
        Page wrapped = new MeterReadingWrapper(meterReadings).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }


    /**
     * 跳转到抄表添加页面
     *
     * @author jiaojiaxiang
     *      * @Date 2019/04/18 10:50
     **/
    @RequestMapping(value = "/add")
    public String roleAdd() {
        return PREFIX + "meterReading_add.html";
    }

    /**
     * 查询商户下拉框
     * @return
     */
    @RequestMapping("/shopData")
    @ResponseBody
    public JSONObject selectShopData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectShopData();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("shopId")), c.get("shopName"));
        }
        return ServerJson;
    }

    @RequestMapping(value = "/addSave")
    @BussinessLog(value = "保存", key = "shopId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData addSave(OrderDto orderDto) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backstageOrderSave";
        String param = JSON.toJSONString(orderDto);
        String result = HttpUtil.post(url,param);
        logger.info(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }


    /**
     * 跳转至审核页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/audit")
    public String meterReadingAudit(@RequestParam String ids,Model model) {
        if (ToolUtil.isEmpty(ids)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        ids = ids.substring(0,ids.lastIndexOf(","));
        model.addAttribute("ids", ids);
        LogObjectHolder.me().set(ids);
        return PREFIX + "meterReading_audit.html";
    }

    /**
     * 审核保存
     */
    @RequestMapping(value = "/pushData")
    @ResponseBody
    public ResponseData pushData(@RequestParam String ids) {
        try {
            ids = ids.substring(0,ids.lastIndexOf(","));
            String[] array = ids.split(",");
            String[] params = dictService.selectByCode("bpm_meter_charge_param").get(0).getDescription().split(",");
            String url = params[0];
            String key = params[1];
            String sec = params[2];
            for(int i=0;i<array.length;i++){
                String id = array[i];
                MeterReading meterReading = meterReadingService.selectById(Integer.parseInt(id));
                if(meterReading.getThrowTime()!=null){
                    continue;
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String dfm = df.format(System.currentTimeMillis());
                TreeMap treeMap = getTreeMapParam(dfm,meterReading,key,sec);
                StringBuilder param = new StringBuilder();
                for (Iterator<Map.Entry<String, String>> it = treeMap.entrySet().iterator(); it.hasNext();) {
                    Map.Entry<String, String> e = it.next();
                    param.append("&").append(e.getKey()).append("=").append(e.getValue());
                }
                String str = param.toString().substring(1);
                logger.info(str);
                String md5Str = BPMInterfaceUtil.MD5(str);
                logger.info(md5Str);
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(treeMap));
                String jsonStr = jsonObject.toString();
                String result = BPMInterfaceUtil.post(url,jsonStr,key,dfm,md5Str);
                logger.info(result);
                JSONObject resultJson = JSONObject.parseObject(result);
                if(Boolean.valueOf(resultJson.get("success").toString())){
                    String chargeNo = resultJson.get("data").toString();
                    meterReading.setReceivablesNumber(chargeNo);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    meterReading.setThrowTime(simpleDateFormat.format(new Date()));
                    meterReading.setAuditStatus("3");
                    if(meterReading.getMeterType()==1||meterReading.getMeterType()==2){
                        MeterDto meter = meterService.selectDataExist(meterReading.getMeterNo());
                        ShiroUser shiroUser = ShiroKit.getUserNotNull();
                        String userId = shiroUser.getId();
                        meter.setUpdateUser(userId);
                        meter.setInitialNum(meterReading.getEndMum());
                        Integer num = meterService.updateMeter(meter);
                    }
                    boolean flag = meterReadingService.updateById(meterReading);
                    if(flag){
                        logger.info("修改成功");
                    }else{
                        throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
                    }
                }else{
                    throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
        }
        return SUCCESS_TIP;


    }
    private TreeMap getTreeMapParam(String dfm, MeterReading meterReading, String key, String sec) throws ParseException {
        TreeMap<String, String> req = new TreeMap<String, String>();
        req.put("app_id", key);
        req.put("app_secret", sec);
        req.put("app_time", dfm);
        Integer meterType = meterReading.getMeterType();
        String name = "";
        if(meterType==1){
            req.put("chargecode", "46");
            name = "水费";
        }else if(meterType==2){
            req.put("chargecode", "48");
            name = "电费";
        }else if(meterType==3){
            req.put("chargecode", "74");
            name = "服务费";
        }else if(meterType==4){
            req.put("chargecode", "74");
            name = "服务费";
        }
        req.put("description", name+"上传");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        req.put("chargedate", sf.format(new Date()));
        req.put("contractno", meterReading.getContractCode());

        req.put("value1", meterReading.getStartMum());
        req.put("value2", meterReading.getEndMum());
        req.put("unitprice", meterReading.getUnitPrice());
        req.put("othervalue", "0");
        req.put("commonvaluetype", "0");
        req.put("powermultiple", meterReading.getTimesRate());
        req.put("remark", "");
        String month = meterReading.getMeterRedingMonth();
        String yearMonth = month.substring(0, 4) + "-" + month.substring(4);
        String yearMonthLastDay = BPMInterfaceUtil.getLastDayOfMonth(yearMonth);
        String nextMonth = BPMInterfaceUtil.monthAddFrist(yearMonth);
        String nextMonthLastDay = BPMInterfaceUtil.getLastDayOfMonth(nextMonth);
        req.put("settleperiodfrom", yearMonth+"-01");
        req.put("settleperiodto", yearMonthLastDay);
        req.put("payduedate", nextMonthLastDay);
        req.put("engerynumber", "");
        req.put("usercode", "WYXT01");
        //折扣
        Double discount = Double.parseDouble(NumberFormat.getPercentInstance().parse(meterReading.getDiscount()).toString()) ;
        req.put("discount" , String.valueOf(discount));

        Double orgamount = Double.valueOf(meterReading.getUnitPrice()) * Double.valueOf(meterReading.getCurrentMum())*Double.valueOf(meterReading.getTimesRate());

        String formatOrganount = String.format("%.2f",orgamount);

        String totalPrice = String.format("%.2f",Double.parseDouble(meterReading.getTotlePrice()));

        Double floatAdjust = Double.parseDouble(totalPrice) - Double.parseDouble(formatOrganount);

        //原含税金额
        req.put("origiamount",formatOrganount);
        //浮动调整额
        req.put("adjamount",String.format("%.2f",floatAdjust));
        //实付金额
        req.put("realpayamount",totalPrice);


        return req;
    }
}
